
package com.platform.modules.mall.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.platform.common.exception.BusinessException;
import com.platform.common.utils.*;
import com.platform.common.validator.AbstractAssert;
import com.platform.modules.mall.dao.MallUserDao;
import com.platform.modules.mall.entity.MallUserEntity;
import com.platform.modules.mall.service.MallUserService;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.faceid.v20180301.models.DetectAuthResponse;
import com.tencentcloudapi.faceid.v20180301.models.DetectInfoText;
import com.tencentcloudapi.faceid.v20180301.models.GetDetectInfoEnhancedResponse;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author
 */
@Service("userService")
public class MallUserServiceImpl extends ServiceImpl<MallUserDao, MallUserEntity> implements MallUserService {
    @Autowired
    JedisUtil jedisUtil;

    @Autowired
    private JedisUtil jedisUtils;


    @Override
    public List<MallUserEntity> queryAll(Map<String, Object> params) {
        return baseMapper.queryAll(params);
    }

    @Override
    public Page queryPage(Map<String, Object> params) {
        //排序
        params.put("sidx", "T.REGISTER_TIME");
        params.put("asc", false);
        Page<MallUserEntity> page = new Query<MallUserEntity>(params).getPage();
        return page.setRecords(baseMapper.selectMallUserPage(page, params));
    }

    @Override
    public boolean add(MallUserEntity mallUser) {
        return this.save(mallUser);
    }

    @Override
    public boolean update(MallUserEntity mallUser) {
        return this.updateById(mallUser);
    }

    @Override
    public boolean delete(Integer id) {
        return this.removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatch(String[] ids) {
        return this.removeByIds(Arrays.asList(ids));
    }

    @Override
    public MallUserEntity queryByMobile(String mobile) {
        return this.getOne(new QueryWrapper<MallUserEntity>().eq("MOBILE", mobile), false);
    }

    @Override
    public MallUserEntity loginByMobile(String mobile, String password) {
        MallUserEntity user = queryByMobile(mobile);
        AbstractAssert.isNull(user, "该手机暂未绑定用户");

        //密码错误
        if (!user.getPassword().equals(DigestUtils.sha256Hex(password))) {
            throw new BusinessException("手机号或密码错误");
        }

        return user;
    }

    @Override
    public MallUserEntity selectByOpenId(String openId) {
        MallUserEntity userEntity = new MallUserEntity();
        userEntity.setOpenId(openId);
        return baseMapper.selectOne(new QueryWrapper<MallUserEntity>().eq("OPEN_ID", openId));
    }

    @Override
    public MallUserEntity saveOrUpdateByOpenId(WxOAuth2UserInfo userWxInfo) {
        MallUserEntity entity = this.getOne(new QueryWrapper<MallUserEntity>().eq("OPEN_ID", userWxInfo.getOpenid()));
        if (entity == null) {
            entity = new MallUserEntity();
            entity.setRegisterTime(new Date());
        }
        entity.setNickname(userWxInfo.getNickname());
        entity.setHeadImgUrl(userWxInfo.getHeadImgUrl());
        entity.setOpenId(userWxInfo.getOpenid());
        entity.setGender(userWxInfo.getSex());
        this.saveOrUpdate(entity);
        return entity;
    }

    @Override
    public RestResponse detectAuth(  String redirectUrl, String userId) throws TencentCloudSDKException {
        String key = "facekey" + userId;
        DetectAuthResponse res = GetDetectInfoEnhanced.detectAuth("AKIDRnxwkWyKTPDrIURAi2ISYbZWRKBI8yl3", "NhyIZNDc5Y0X3c5gAZrxsfGh4SrEa5Vk",
                "2", "430321199806152716", "赵旺", redirectUrl);
        String bizToken = res.getBizToken();
        JSONObject js = new JSONObject();
        js.put("idCard", "430321199806152716");
        js.put("name", "赵旺");
        js.put("redirectUrl", redirectUrl);
        js.put("bizToken", bizToken);
        js.put("detectAuth", false);
        jedisUtils.setObject(key, js, 2 * 3600);

        return RestResponse.success().put("detectAuthInfo", res);
    }


    @Override
    public RestResponse detectAuthGetRes(String userId) {
        String key = "facekey" + userId;
        if (!jedisUtils.exists(key)) {
            return RestResponse.success().put("detectAuth", false);
        }

        JSONObject object = (JSONObject) jedisUtils.getObject(key);
        if (object.getBoolean("detectAuth")) {
            return RestResponse.success().put("detectAuth", true).put("detectAuthInfo", object);
        }
        String bizToken = object.getString("bizToken");

        GetDetectInfoEnhancedResponse res;
        try {
            res = GetDetectInfoEnhanced.getDetectInfoEnhanced( "AKIDRnxwkWyKTPDrIURAi2ISYbZWRKBI8yl3",
                    "NhyIZNDc5Y0X3c5gAZrxsfGh4SrEa5Vk" , "2", bizToken);
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
            throw new BusinessException("人脸活体认证结果获取失败！");
        }

        DetectInfoText text = res.getText();
        if (text.getErrCode() == null || !text.getErrCode().equals(0L)) {
            return RestResponse.error(413, res.getText().getErrMsg()).put("detectAuth", false).put("userCardInfo", object);
        }
        object.put("detectAuth", true);
        jedisUtils.setObject(key, object, 2 * 3600);
        return RestResponse.success().put("detectAuth", true).put("detectAuthInfo", object);
    }
}
